# coding: utf-8
import socket
import logging
import platform


def sysEncode(val):
	"""

	根据系统转换编码
	"""
	if platform.system() == 'Windows':
		return unicode(val, 'utf-8').encode('gbk')
	else:
		return val

def customLogging(**kwargs):
	"""

	自定义日志格式
	"""
	level_dict = {
		'notset': 0,
		'debug': 10,
		'info': 20,
		'warning': 30,
		'error': 40,
		'critical': 50,
		}

	logging_file 	= kwargs.get('logging_file', None)
	mode 			= kwargs.get('mode', 'a')
	asctime 		= kwargs.get('asctime', False)
	levelname 		= kwargs.get('levelname', False)
	level 			= kwargs.get('level', 'info')
	console 		= kwargs.get('console', False)

	format_ = '[PID: %(process)d] %(message)s'
	format_ = ('[%(levelname)s] ' + format_) if levelname else format_
	format_ = ('[%(asctime)s] ' + format_) if asctime else format_

	logging.basicConfig(
		level=level_dict.get(level, 20),
		format=format_,
		datefmt='%Y-%m-%d %H:%M:%S',
		filename=logging_file,
		filemode=mode,
		encoding=kwargs.get('encoding', 'utf8')
		)

	if console:
		console = logging.StreamHandler()
		console.setLevel(logging.INFO)
		formatter = logging.Formatter(format_)
		console.setFormatter(formatter)
		logging.getLogger('').addHandler(console)

	return logging

logging = customLogging(asctime=True)

def udpSocketServer(**kwargs):
	"""

	SOCKET UDP 服务端
	"""
	ip = kwargs.get('ip', '127.0.0.1')
	port = kwargs.get('port', 10021)
	
	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #创建一个socket,SOCK_DGRAM表示UDP
	sock.bind((ip, port))                         #绑定IP地址及端口
	logging.info(sysEncode('Bound UDP on %s...' % (port)))
	
	return sock

def udpSocketClient():
	"""

	SOCKET UDP 客户端
	"""
	logging.info(sysEncode('create UDP client socket...'))
	return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 

TEST = 'test'
BUF_SIZE = 1024